<!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webgl - interactive - voxel painter</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <style>
        body {
            font-family: Monospace;
            background-color: #f0f0f0;
            margin: 0px;
            overflow: hidden;
        }

        #oldie { background-color: #ddd !important }
    </style>
</head>
<body>

<script src="../js/three.js"></script>
<script src="../js/stats.min.js"></script>
<script src="../js/Detector.js"></script>
<script src="../js/loaders/OBJLoader.js"></script>
<div id="panel_info">
    <label>介绍</label><br>
    <label id="txt_info">详细信息</label>
</div>
<script>

    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

    var container;
    var camera, scene, renderer;
    var plane, cube;
    var mouse, raycaster, isShiftDown = false;
    var isCtrlDown = false
    var isMouseDown = -1

    var rollOverMesh, rollOverMaterial;
    var cubeGeo, cubeMaterial;

    var objects = [];
    var stats

    var clickPosition = new THREE.Vector3()
    var cameraCenterPosition = new THREE.Vector3()

    var panel_info, txt_info

    init();
    render();

    function init() {

        container = document.createElement( 'div' );
        document.body.appendChild( container );
        container.style.top = '0px'


        stats = new Stats()
        container.appendChild(stats.dom)

        var info = document.createElement( 'div' );
        info.style.position = 'absolute';
        info.style.top = '10px';
        info.style.width = '100%';
        info.style.textAlign = 'center';
        info.innerHTML = '<a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - voxel painter - webgl<br><strong>click</strong>: add voxel, <strong>shift + click</strong>: remove voxel';
        container.appendChild( info );

        panel_info = document.getElementById("panel_info")
        panel_info.parentNode.removeChild(panel_info)
        container.appendChild(panel_info)
        txt_info = document.getElementById("txt_info")

        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.set( 500, 800, 1300 );
        camera.lookAt( new THREE.Vector3() );

        scene = new THREE.Scene();
        scene.background = new THREE.Color( 0xf0f0f0 );

        // roll-over helpers

        var rollOverGeo = new THREE.BoxGeometry( 50, 50, 50 );
        rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
        rollOverMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
        scene.add( rollOverMesh );

        // cubes

        cubeGeo = new THREE.BoxGeometry( 50, 50, 50 );
        cubeMaterial = new THREE.MeshLambertMaterial( { color: 0xfeb74c, map: new THREE.TextureLoader().load( "../textures/square-outline-textured.png" ) } );

        // grid

        var gridHelper = new THREE.GridHelper( 10000, 200 );
        scene.add( gridHelper );

        //

        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2();

        var geometry = new THREE.PlaneBufferGeometry( 10000, 10000 );
        geometry.rotateX( - Math.PI / 2 );

        plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
        scene.add( plane );

        objects.push( plane );

        // Lights

        var ambientLight = new THREE.AmbientLight( 0x606060 );
        scene.add( ambientLight );

        var directionalLight = new THREE.DirectionalLight( 0xffffff );
        directionalLight.position.set( 1, 0.75, 0.5 ).normalize();
        scene.add( directionalLight );

        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );

        // 加载场景
        var manager = new THREE.LoadingManager();
        manager.onProgress = function( item, loaded, total ) {

            console.log( item, loaded, total );

        };
        var loader = new THREE.OBJLoader( manager );
        loader.load( '../models/zhoushan.obj', function( object ) {

            object.position.y = 0;
            scene.add( object );
            console.log("加载fbx成功！")

        }, function (xhr) {

            if ( xhr.lengthComputable ) {

                var percentComplete = xhr.loaded / xhr.total * 100;
                console.log( Math.round( percentComplete, 2 ) + '% downloaded' );

            }
        }, function (xhr) {
            console.log("加载fbx失败！"+xhr)
        } );



        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        document.addEventListener( 'mousedown', onDocumentMouseDown, false );
        document.addEventListener( 'keydown', onDocumentKeyDown, false );
        document.addEventListener( 'keyup', onDocumentKeyUp, false );
        document.addEventListener('wheel', _mousewheel, false );
        document.addEventListener( 'mouseup', onDocumentMouseUp, false );
        document.addEventListener( 'contextmenu', onContextMenu, false );

        //

        window.addEventListener( 'resize', onWindowResize, false );

    }
    function onContextMenu(event) {
        event.preventDefault();
    }
    function _mousewheel(event) {
        console.log("mouse wheel. delta=" + event.wheelDelta)

        // 缩放摄像机
        factor = 1
        if (event.wheelDelta < 0) {
            factor = -1
        }

        // 向forward方向移动delta
        xaxis = new THREE.Vector3, yaxis = new THREE.Vector3, zaxis = new THREE.Vector3
        camera.matrixWorld.extractBasis(xaxis, yaxis, zaxis)

        console.log(xaxis)

        zaxis.multiplyScalar(factor * -40)

        camera.position.add(zaxis)
        // camera.position.y += factor * 5;
        // camera.updateProjectionMatrix();


        // 阻止将事件传递给下一层
        event.preventDefault();
    }

    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

    }

    lastx = 0
    lasty = 0

    function onDocumentMouseMove( event ) {

        event.preventDefault();

        mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );

        raycaster.setFromCamera( mouse, camera );

        var intersects = raycaster.intersectObjects( objects );

        if ( intersects.length > 0 ) {

            var intersect = intersects[ 0 ];

            rollOverMesh.position.copy( intersect.point ).add( intersect.face.normal );
            rollOverMesh.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );

        }

        render();


        deltax = 0
        deltay = 0
        if(this.lastx == 0 && this.lasty == 0) {

        } else {
            deltax = event.x - this.lastx
            deltay = event.y - this.lasty
        }
        this.lastx = event.x
        this.lasty = event.y

        if(isMouseDown == 0) {

            factor = 1

            // 向forward方向移动delta
            xaxis = new THREE.Vector3, yaxis = new THREE.Vector3, zaxis = new THREE.Vector3
            camera.matrixWorld.extractBasis(xaxis, yaxis, zaxis)

            // console.log(xaxis)
            // yaxis.add(zaxis)
            // yaxis = zaxis
            yaxis.copy(xaxis)
            yaxis.cross(new THREE.Vector3(0,1,0))

            if (Math.abs(deltax) > Math.abs(deltay) )
            {
                if (deltax > 0) {
                    xaxis.multiplyScalar(-1)
                }
                xaxis.multiplyScalar(10)
                camera.position.add(xaxis)
            } 
            else 
            {   
                if(deltay > 0) {
                    yaxis.multiplyScalar(-1)
                }        
                yaxis.multiplyScalar(10)     
                camera.position.add(yaxis)
            }
        } else if(isMouseDown == 2) {

            var baseOnClickPos = false
            var axis = new THREE.Vector3(0,1,0)
            var angle = 0.01

            var mypos = new THREE.Vector3
            var q = new THREE.Quaternion()
            var pos = new THREE.Vector3

            if (!baseOnClickPos) {
                pos.copy(cameraCenterPosition)
                baseOnClickPos = true
            } else {
                pos.copy(clickPosition)
            }


            //var m = new THREE.Quaternion()

            if(Math.abs(deltax) > Math.abs(deltay)) {
                if(deltax > 0) {
                    angle = angle * -1
                }
                axis = new THREE.Vector3(0,1,0)
            } else {
                if(deltay < 0) {
                    angle = angle * -1
                }
                xaxis = new THREE.Vector3, yaxis = new THREE.Vector3, zaxis = new THREE.Vector3
                camera.matrixWorld.extractBasis(xaxis, yaxis, zaxis)
                axis.copy(xaxis)
            }

            q.setFromAxisAngle(axis, angle)

            mypos.copy(camera.position)
            mypos.sub(pos)
            mypos.applyQuaternion(q)
            mypos.add(pos)
            camera.position.copy(mypos)

            q.copy(camera.quaternion)
            q.inverse()
            axis.applyQuaternion(q)
            camera.rotateOnAxis(axis, angle)


        }


    }

    function onDocumentMouseUp( event ) {

        event.preventDefault();
        isMouseDown = -1
    }
    function onDocumentMouseDown( event ) {

        event.preventDefault();
        isMouseDown = event.button


        // 记录摄像机屏幕中心点的世界坐标位置
        mouse.set( ( 0.5 ) * 2 - 1, - ( 0.5 ) * 2 + 1 );
        raycaster.setFromCamera( mouse, camera );
        var intersects = raycaster.intersectObjects( objects );
        if ( intersects.length > 0 ) {
            var intersect = intersects[ 0 ];
            cameraCenterPosition.copy(intersect.point)
        }

        mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );

        raycaster.setFromCamera( mouse, camera );

        var intersects = raycaster.intersectObjects( objects );

        if ( intersects.length > 0 ) {

            var intersect = intersects[ 0 ];
            clickPosition.copy(intersect.point)
            // delete cube

            if ( isShiftDown ) {

                if ( intersect.object != plane ) {

                    scene.remove( intersect.object );

                    objects.splice( objects.indexOf( intersect.object ), 1 );

                }

                // create cube

            } else if (isCtrlDown) {

                var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
                voxel.position.copy( intersect.point ).add( intersect.face.normal );
                voxel.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
                scene.add( voxel );

                objects.push( voxel );

            }

            render();

        }

        // 将信息移动到点击的位置
        panel_info.style.position = 'absolute'
        panel_info.style.left = event.clientX + 'px'
        panel_info.style.top = event.clientY + 'px'
        txt_info.innerHTML = "世界坐标：" + clickPosition.x.toFixed(2) + "," + clickPosition.z.toFixed(2)
        console.log("123", event.clientX, event.clientY)
    }

    function onDocumentKeyDown( event ) {

        console.log(event.keyCode)

        switch( event.keyCode ) {

            case 16: isShiftDown = true; break;
            case 17: isCtrlDown = true;break;
        }

    }

    function onDocumentKeyUp( event ) {

        switch ( event.keyCode ) {

            case 16: isShiftDown = false; break;
            case 17: isCtrlDown = false; break;
        }

    }

    function render() {

        renderer.render( scene, camera );

    }

    var animate = function () {
        requestAnimationFrame( animate );

        stats.update();

        // 显示场景内容
        render()
    };

    animate();

</script>

</body>
</html>
